import React, {Component } from 'react';
import {connect} from 'react-redux'
import { Card,Button,Table,message,Modal,Form, Input,Tree,Row,Col } from 'antd';
import {reqRoleList,reqAddRoles,reqUpdateRoles} from '../../api/index.js'
import dayjs from 'dayjs'

class Role extends Component {
  state = {
    roleList: [],  // 角色列表
    visible: false,   // 添加角色模态对话框是否可见
    treeVisible: false,   // tree更新角色(给角色设置权限)模态对话框是否可见
    updateRoleInfo: {},  //点击更新的角色信息
    checkedKeys: [],    // 选中的节点
  }
  render() {
    let {roleList,updateRoleInfo,checkedKeys} = this.state
    
    // table表格配置参数
    const columns = [
      {
        title: '角色名称',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '创建时间',
        dataIndex: 'create_time',
        key: 'create_time',
        render: (time) => dayjs(time).format('YYYY-MM-DD HH:mm:ss')
      },
      {
        title: '授权时间',
        dataIndex: 'auth_time',
        key: 'auth_time',
        render: (time) => time ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : ''
      },
      {
        title: '授权人',
        dataIndex: 'auth_name',
        key: 'auth_name'
      },
      {
        title: '操作',
        render: (item) => {
          return <Button type="link" onClick={()=>{this.updateRole(item)}}>设置权限</Button>
        }
      }
    ];
    
    // tree
    const treeData = [
      {
        title:'平台权限',
        key:0,
        children:[
          {
            title: '首页',
            key: '/home',
          },
          {
            title: '商品',
            key: '/products',
            children: [
              {
                title: '分类管理',
                key: '/category',
              },
              {
                title: '商品管理',
                key: '/product',
              }
            ],
          },
          {
            title: '用户管理',
            key: '/user',
          },
          {
            title: '角色管理',
            key: '/role',
          },
          {
            title: '图形图标',
            key: '/charts',
            children: [
              {
                title: '柱状图',
                key: '/bar',
              },
              {
                title: '折线图',
                key: '/line',
              },
              {
                title: '饼状图',
                key: '/pie',
              }
            ]
          },
        ]
      }
    ];
    
    return <div>
      <Card title={<Button type="primary" onClick={() => {
        this.setState({visible: true})
      }}>添加角色</Button>}>
        <Table dataSource={roleList} columns={columns} rowKey="_id" bordered/>
      </Card>
      
      {/*添加角色模态对话框*/}
      <Modal
        title="添加角色"
        visible={this.state.visible}
        onOk={this.handleOk}
        onCancel={() => {
          this.setState({visible: false})
        }}
      >
        <Form ref={(form) => this.roleNameForm = form}>
          <Form.Item
            label="角色名称"
            name="roleName"
            rules={[{required: true, message: '角色名称必须输入!'}]}
          >
            <Input placeholder="请输入角色名称"/>
          </Form.Item>
        </Form>
      </Modal>
      
      {/* 更新角色(给角色设置权限)*/}
      <Modal
        title="设置角色权限"
        visible={this.state.treeVisible}
        onOk={this.treeHandleOk}
        onCancel={this.treeCancel}
      >
        <Row>
          <Col span={4}>角色名称：</Col>
          <Col span={20}><Input value={updateRoleInfo.auth_name} disabled/></Col>
        </Row>
        <br/>
        <br/>
        <Tree
          defaultExpandAll
          checkable
          onCheck={this.onCheck}
          checkedKeys={checkedKeys}
          treeData={treeData}
        >
        </Tree>
      </Modal>
    </div>
  }
  
  componentDidMount() {
    // 获取角色列表
    this.getRoleList()
  }
  
  // 获取角色列表
  getRoleList = async () => {
    let res = await reqRoleList()
    let {data, status, msg} = res
    if (status === 0) {
      this.setState({
        roleList: data
      })
    } else {
      message.error(msg, 1)
    }
  }
  
  // 添加角色模态对话框ok
  handleOk = () => {
    this.roleNameForm.validateFields()
      .then(async value => {  // 验证通过
        let {roleName} = value
        let res = await reqAddRoles(roleName)  //添加角色
        let {status, msg} = res
        if (status === 0) {   //添加角色成功
          message.success('添加角色成功！', 1)
          this.setState({
            visible: false,
          });
          this.getRoleList()
        } else {  //添加角色失败
          message.error(msg, 1)
        }
      })
      .catch(errorInfo => {   // 验证失败
        message.error(errorInfo.errorFields[0].errors[0], 1)
      })
  };
  
  // 给角色设置权限
  updateRole = (item) => {
    let menus = item.menus
    let checkedKeys = this.state.checkedKeys
    menus.forEach(item => {
      checkedKeys.push(item)
    })
    this.setState({
      treeVisible: true,
      updateRoleInfo: item,
      checkedKeys:checkedKeys
    })
  }
  
  // tree模态对话框点击cancel
  treeCancel = ()=>{
    this.setState({
      treeVisible: false,
      updateRoleInfo: {},
      checkedKeys:[]
    })
  }
  
  // 给角色设置权限点击ok提交设置
  treeHandleOk = async () => {
    let {username} = this.props.userInfo.user
    let {updateRoleInfo,checkedKeys} = this.state
    console.log(checkedKeys)
    let {_id} = updateRoleInfo
    let res = await reqUpdateRoles({_id,auth_time:Date.now(),auth_name:username,menus:checkedKeys})
    let {status,msg} = res
    if (status===0){  // 获取成功
      message.success("角色权限更新成功！",1)
      this.setState({
        treeVisible: false,
        updateRoleInfo: {},
        checkedKeys:[],
      })
      // 重新获取角色列表
      this.getRoleList()
    } else {  // 获取失败
      message.error(msg,1)
    }
  }
  
  // 选中的节点
  onCheck = (checkedKeys) => {
    this.setState({
      checkedKeys
    })
  };
}

export default connect(
  state => ({userInfo : state.userInfo})
)(Role)
